<?php

namespace App\Http\Controllers\VideoApi;

use App\Http\Config\ErrorCode;
use App\Models\video\BroadcasterModel;
use App\Models\video\BroadcasterRelationModel;
use App\Models\video\CommentModel;
use App\Models\video\CommonServer;
use App\Models\video\CourseCatalogModel;
use App\Models\video\CourseModel;
use App\Models\video\DynamicModel;
use App\Models\video\PlayClassModel;
use App\Models\video\PlayListModel;
use Illuminate\Http\Request;
use App\Library\UpTools;
use App\Models\video\VodApis;
use App\Models\video\VodHandle;
use App\Models\video\VodVideoModel;

class VodMediaController extends BaseController
{
    public function __construct(Request $request)
    {
        $this->noCheckTokenAction = ['eventNotify']; //不校验openid
        parent::__construct($request);
    }

    // 上传媒体文件
    public function uploadFile(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        $broadcasterData = BroadcasterModel::from(BroadcasterModel::query()->getModel()->getTable()." as b")
            ->leftJoin(BroadcasterRelationModel::query()->getModel()->getTable()." as br", "b.id", "=", "br.broadcaster_id")
            ->select("b.id","b.status")
            ->where(["b.status" => 1, "b.mall_id" => request()->mallData["id"], "br.user_id" => $request->userLoginData["id"]])
            ->first();
        if(empty($broadcasterData)){
            $this->returnData = ErrorCode::$admin_enum['fail'];
            $this->returnData['msg'] = 'up主信息不存在，请联系管理员';
            return $this->return_result($this->returnData);
        }
        if($broadcasterData["status"] != '1'){
            $this->returnData = ErrorCode::$admin_enum['fail'];
            $this->returnData['msg'] = 'up主已经禁用，无法操作';
            return $this->return_result($this->returnData);
        }
        global $scf_data;
        $file = $request->file;
        if (empty($file)) {
            $returnData = ErrorCode::$admin_enum['params_error'];
            $returnData['msg'] = '缺少文件';
            return $this->return_result($returnData);
        }
        $uploadList = [];
        if(!empty($scf_data["host"])) {
            $temp_file = tempnam(sys_get_temp_dir(), "php");  //临时文件
            file_put_contents($temp_file, base64_decode($file['content']));        //文件流写入文件
            $uploadList["fileType"] = UpTools::getFileType($file["name"]);
            $uploadList["filePath"] = $temp_file;
        }else{
            $uploadList["fileType"] = UpTools::getFileType($file->getClientOriginalName());
            $uploadList["filePath"] = $file->getPathname();
        }
        $res = VodApis::getInstance()->uploadMediaFile($uploadList);
        if($res["code"] != '0'){
            return $this->return_result($res);
        }else{
            $id = VodVideoModel::toAdd(["vid" => $res["data"]["FileId"], "media_url" => $res["data"]["MediaUrl"], "broadcaster_id" => $broadcasterData["id"], "status" => 0], true);
            $this->returnData["data"] = ["id" => $id];
        }
        return $this->return_result($this->returnData);
    }

    // 完善媒体信息
    public function saveMediaInfo(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        if(empty($request->id)){
            return $this->return_result(ErrorCode::code("params_not_exist", "视频ID"));
        }
        $database = VodVideoModel::query()->select("id","vid","video_duration","broadcaster_id","video_url_list","handle_result")
            ->where("id", $request->id)->orWhere("vid", $request->id)->first();
        if(empty($database)){
            $broadcasterData = BroadcasterRelationModel::getFields("broadcaster_id", ["user_id" => $request->userLoginData["id"]], true, false);
            $request->id = VodVideoModel::toAdd(["vid" => $request->id, "media_url" => "", "broadcaster_id" => $broadcasterData["broadcasterId"], "status" => 0], true);
            $database = VodVideoModel::getFields("id,vid,video_duration,broadcaster_id,video_url_list,handle_result", ["id" => $request->id], true,false);
        }else{
            $database = VodVideoModel::transferField($database->toArray());
            $request->id = $database["id"];
        }
        if(empty($request->title)){
            return $this->return_result(ErrorCode::code("params_not_exist", "视频标题"));
        }
        $data = [
            "title" => mb_substr($request->title, 0, 120), "status" => 1, "pay_mode" => $request->payMode ?: 0, "type" => $request->type ?: 1,
            'cat_id' => $request->catId ?: 0, "desc" => "", "file_type" => $request->fileType ? explode("/", $request->fileType)[0] : ""
        ];
        if(!empty($request->desc)){
            $data["desc"] = mb_substr($request->desc, 0, 300);
        }
        if(!empty($request->coverImgId)){
            $data["cover_img_id"] = $request->coverImgId;
        }
        if(!empty($request->tryTime)){
            $data["try_time"] = $request->tryTime;
        }
        if(!empty($request->payMoney)){
            $data["pay_money"] = $request->payMoney;
        }
        $res = VodApis::getInstance()->modifyMediaInfo($database["vid"], UpTools::transferFields($data));
        if($res["code"] == '0') {
            if($request->payMode == '1'){
                $data["member_mode"] = $request->memberMode ?: '0'; // 会员优惠，0免费，1折扣
            }elseif($request->payMode == '2'){ // 会员免费
                $data["member_mode"] = '0'; // 会员优惠，0免费
            }
            if(VodVideoModel::doUpdate($data, ["id" => $request->id])){
                if(!$request->operateType == 'update') { // 添加新视频
                    if(!DynamicModel::query()->where(["belong_id" => $request->id, "type" => 2])->count()) { // 发布普通视频
                        DynamicModel::toAdd([
                            "broadcaster_id" => $database["broadcasterId"], "belong_id" => $request->id,
                            "contents" => $request->dynamicText, "type" => 2, "status" => !empty($database["videoUrlList"]) ? 1 : 0
                        ]);
                    }
                    $videoCount = VodVideoModel::query()->where("broadcaster_id", $database["broadcasterId"])->where("handle_result", "<>", 3)->count();
                    BroadcasterModel::doUpdate(["video_count" => $videoCount], ["id" => $database["broadcasterId"]]);
                    if(!empty($database["videoUrlList"])){
                        VodHandle::getInstance()->sendWxTemplate($data, $request->mallData["id"], $database["broadcasterId"]);
                    }
                }
                if ($request->classId) {
                    $res = PlayListModel::query()->select("id", "class_id as classId")
                        ->where(["mall_id" => $request->mallData["id"], "video_id" => $request->id, "broadcaster_id" => $database["broadcasterId"]])
                        ->first();
                    if (!empty($res->id)) {
                        if ($res->classId != $request->classId) {
                            $res = json_decode(json_encode($res), true);
                            PlayListModel::delById($res->id, $res);
                            PlayListModel::toAdd(["broadcaster_id" => $database["broadcasterId"], "video_id" => $request->id, "class_id" => $request->classId]);
                        }
                    } else {
                        PlayListModel::toAdd(["broadcaster_id" => $database["broadcasterId"], "video_id" => $request->id, "class_id" => $request->classId]);
                    }
                }elseif($request->courseId){
                    $res = CourseModel::query()->from(CourseModel::query()->getModel()->getTable()." as c")
                        ->leftJoin(CourseCatalogModel::query()->getModel()->getTable()." as cc", "c.id", "=", "cc.course_id")
                        ->where(["cc.video_id" => $request->id])
                        ->select("cc.course_id")
                        ->first();
                    if(empty($res->course_id)){
                        CourseCatalogModel::toAdd(["course_id" => $request->courseId, "broadcaster_id" => $database["broadcasterId"], "video_id" => $request->id]);
                    }elseif($res->course_id != $request->courseId){
                        CourseCatalogModel::delByFilter(['course_id' => $res->course_id, "video_id" => $request->id]);
                        CourseCatalogModel::toAdd(["course_id" => $request->courseId, "broadcaster_id" => $database["broadcasterId"], "video_id" => $request->id]);
                    }
                }
            }
        }else{
            $this->returnData = $res;
        }
        return $this->return_result($this->returnData);
    }

    // 我的视频
    public function getMyMedia(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        $type = $request->type ? 1 : 2; // 1 处理中 0 已处理
        if(!$broadcasterId = CommonServer::judgeUpIdentity($request->userLoginData["id"], $request->mallData["id"])){
            $this->returnData = ErrorCode::$admin_enum['params_error'];
            $this->returnData['msg'] = 'up主信息不存在，请联系管理员';
            return $this->return_result($this->returnData);
        }
        $field = "id,title,desc,cover_img_id,create_time,view_count,video_length,review_content,status,pay_mode,pay_money,type,file_type";
        $data = VodVideoModel::getList($field, ["handle_result" => $type, "broadcaster_id" => $broadcasterId, "status" => 1], $request->page ?: 1, $request->pageSize ?: 20);
        foreach ($data["list"] as &$item){
            $item["commentCount"] = CommentModel::getCount(["belong_id" => $item["id"], "status" => 1, "type" => 1]); // 评论次数
            $item["likeCount"] = PlayListModel::getCount(["class_id" => -1, 'mall_id' => $request->mallData["id"], "video_id" => $item["id"]]); // 点赞次数
        }
        $this->returnData["data"] = $data;
        return $this->return_result($this->returnData);
    }

    // 获取媒体信息
    public function getMediaInfo(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        $data = VodVideoModel::getFields("*", ["id" => $request->id]);
        if(!empty($data)){
            if($data["type"] == '1') { // 普通视频
                $res = PlayListModel::query()->from(PlayListModel::query()->getModel()->getTable() . " as pl")
                    ->leftJoin(PlayClassModel::query()->getModel()->getTable() . " as pc", "pc.id", "=", "pl.class_id")
                    ->where(["pl.mall_id" => $request->mallData["id"], "pl.video_id" => $request->id, "pl.broadcaster_id" => $data["broadcasterId"]])
                    ->select("pc.id as classId", "pc.name as className")->first();
                $res = json_decode(json_encode($res), true);
                $this->returnData["data"] = is_array($res) ? array_merge($data, $res) : $data;
            }else{ // 课程
                $res = CourseModel::query()->from(CourseModel::query()->getModel()->getTable()." as c")
                    ->leftJoin(CourseCatalogModel::query()->getModel()->getTable()." as cc", "c.id", "=", "cc.course_id")
                    ->where(["cc.video_id" => $request->id, "c.mall_id" => $request->mallData["id"], "c.broadcaster_id" => $data["broadcasterId"]])
                    ->select("c.id as courseId", "c.name as courseName")
                    ->first();
                $res = json_decode(json_encode($res), true);
                $this->returnData["data"] = is_array($res) ? array_merge($data, $res) : $data;
            }
        }else{
            $this->returnData["data"] = [];
        }
        return $this->return_result($this->returnData);
    }

    // 同步删除媒体
    public function deleteMedia(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        if($request->userLoginData["userType"] != '1'){
            $this->returnData = ErrorCode::$admin_enum['params_error'];
            $this->returnData['msg'] = '用户不是up主，无法上传媒体';
            return $this->return_result($this->returnData);
        }
        if(!$broadcasterId = CommonServer::judgeUpIdentity($request->userLoginData["id"], $request->mallData["id"])){
            $this->returnData = ErrorCode::$admin_enum['params_error'];
            $this->returnData['msg'] = 'up主信息不存在，请联系管理员';
            return $this->return_result($this->returnData);
        }
        VodVideoModel::delByFilter(["id" => $request->id, "broadcaster_id" => $broadcasterId]);
        return $this->returnData;
    }

    // 媒体通知回调地址
    public function eventNotify(){
        try {
            $this->returnData = VodHandle::getInstance()->handleData(request()->post());
        }catch (\Exception $e){
            UpTools::writeLog("sdf：".var_export($e->getMessage()).$e->getTraceAsString(), "notifyError.txt");
        }
        return $this->return_result($this->returnData);
    }
}
